package com.ruoyi.ora.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.dict.DevicePermission;
import com.ruoyi.common.enums.dict.DeviceUserStatus;
import com.ruoyi.common.enums.dict.UserMessageType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ora.domain.*;
import com.ruoyi.ora.mapper.DeviceMapper;
import com.ruoyi.ora.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备Service业务层处理
 * 
 * @author liuwp
 * @date 2024-11-14
 */
@Service
public class DeviceServiceImpl implements IDeviceService
{
    private static final Logger log = LoggerFactory.getLogger(DeviceServiceImpl.class);
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private IVoiceStoryService voiceStoryService;
    @Autowired
    private IVoiceMemoirService voiceMemoirService;
    @Autowired
    private IVoiceRecordService voiceRecordService;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectDeviceById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 根据业务主键查询一条记录：设备
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public Device selectOneDevice(Device device)
    {
        return deviceMapper.selectOneDevice(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insertDevice(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateDevice(device);
    }

    @Override
    public int updateDeviceCondition(Device device, Device deviceCondition)
    {
                device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateDeviceCondition(device, deviceCondition);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteDeviceByIds(ids);
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteDeviceById(id);
    }

    /**
     * 条件删除设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int deleteDeviceByCondition(Device device)
    {
        return deviceMapper.deleteDeviceByCondition(device);
    }

    @Override
    public AjaxResult deviceBindHandle(DeviceUser deviceUser) {
        // 设备绑定应该是传过来设备的sn
        if (StringUtils.isNotEmpty(deviceUser.getDeviceSn())){
            Device device1 = selectOneDevice(Builder.of(Device::new).with(Device::setDeviceSn, deviceUser.getDeviceSn()).build());
            if (device1 != null){
                // TODO 这里考虑加上锁 万一绑定重复操作
                // 判断用户是否已经绑定过该设备
                DeviceUser build1 = Builder.of(DeviceUser::new)
                        .with(DeviceUser::setDeviceId, device1.getId())
                        .with(DeviceUser::setUserId, deviceUser.getUserId())
                        .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                        .build();
                DeviceUser deviceUser1 = deviceUserService.selectOneDeviceUser(build1);

                build1.setDeviceName(deviceUser.getDeviceName());
                build1.setDeviceRelationId(deviceUser.getDeviceRelationId());
                build1.setTerminalId(deviceUser.getTerminalId());
                build1.setOperId(deviceUser.getUserId());
                if (deviceUser1 == null){
                    // 如果没有绑定过 判断这个设备有没有管理员
                    DeviceUser build2 = Builder.of(DeviceUser::new)
                            .with(DeviceUser::setDeviceId, device1.getId())
                            .with(DeviceUser::setDevicePermission, DevicePermission.ADMIN.getValue())
                            .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                            .build();
                    DeviceUser deviceUser2 = deviceUserService.selectOneDeviceUser(build2);
                    if (deviceUser2 == null){
                        build1.setDevicePermission(DevicePermission.ADMIN.getValue());
                    }else {
                        build1.setDevicePermission(DevicePermission.MEMBER.getValue());
                    }
                    deviceUserService.insertDeviceUser(build1);

                    userMessageService.insertUserMessage(Builder.of(UserMessage::new)
                            .with(UserMessage::setUserId, deviceUser.getUserId())
                            .with(UserMessage::setMsgType, UserMessageType.BIND_DEVICE.getValue())
                            .with(UserMessage::setAssetsId1, device1.getId().toString())
                            .with(UserMessage::setAssetsId1, device1.getDeviceSn().toString())
                            .with(UserMessage::setMsgTitle, "设备【"+deviceUser.getDeviceName()+"】绑定成功").build());
                }else {
                    build1.setId(deviceUser1.getId());
                    deviceUserService.updateDeviceUser(build1);
                }
                return AjaxResult.success();

            }else {
                return AjaxResult.error(MessageUtils.message("ora.device.notexist"));
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }

    }

    @Override
    public AjaxResult deviceUnbindHandle(Device device, SysUser sysUser) {
        if (device.getId() != null){
            DeviceUser build = Builder.of(DeviceUser::new)
                    .with(DeviceUser::setDeviceId, device.getId())
                    .with(DeviceUser::setUserId, sysUser.getUserId())
                    .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                    .build();
            DeviceUser deviceUser = deviceUserService.selectOneDeviceUser(build);

            if (deviceUser != null){
                deviceUser.setStatus(DeviceUserStatus.UNBIND.getValue());
                int i = deviceUserService.updateDeviceUser(deviceUser);
                if (i > 0){
                    userMessageService.insertUserMessage(Builder.of(UserMessage::new)
                            .with(UserMessage::setUserId, deviceUser.getUserId())
                            .with(UserMessage::setMsgType, UserMessageType.UNBIND_DEVICE.getValue())
                            .with(UserMessage::setAssetsId1, device.getId().toString())
                            .with(UserMessage::setAssetsId1, device.getDeviceSn().toString())
                            .with(UserMessage::setMsgTitle, "设备【"+deviceUser.getDeviceName()+"】解绑成功").build());
                    // 解绑管理员转移
                    if (device.getAdminUserId() != null){
                        DeviceUser deviceUser1 = deviceUserService.selectDeviceUserById(device.getAdminUserId());
                        if (deviceUser1 != null){
                            deviceUser1.setDevicePermission(DevicePermission.ADMIN.getValue());
                            deviceUserService.updateDeviceUser(deviceUser1);
                        }
                    }

                    return AjaxResult.success();
                }else {
                    return AjaxResult.error(MessageUtils.message("ora.common.error"));
                }
            }else {
                return AjaxResult.error(MessageUtils.message("ora.device.nobind"));
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }

    @Override
    public AjaxResult deviceMineList(Device device, SysUser sysUser) {
        // TODO 因为我的设备不会太多 暂时简单写了  如果需要优化再改
        DeviceUser build = Builder.of(DeviceUser::new)
                .with(DeviceUser::setUserId, sysUser.getUserId())
                .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                .build();
        List<DeviceUser> deviceUsers = deviceUserService.selectDeviceUserList(build);

        for (DeviceUser deviceUser : deviceUsers) {
            deviceUser.setDevice(selectDeviceById(deviceUser.getDeviceId()));

            // 获取设备的管理员
            DeviceUser build1 = Builder.of(DeviceUser::new)
                    .with(DeviceUser::setDeviceId, deviceUser.getDeviceId())
                    .with(DeviceUser::setStatus, DeviceUserStatus.BIND.getValue())
                    .with(DeviceUser::setDevicePermission, DevicePermission.ADMIN.getValue())
                    .build();

            DeviceUser deviceUser1 = deviceUserService.selectOneDeviceUser(build1);
            if (deviceUser1 != null){
                deviceUser.setSysUser(sysUserService.selectUserById(deviceUser1.getUserId()));
            }
        }
        return AjaxResult.success(deviceUsers);
    }

    @Override
    public void deviceFamilyCircleDataMigration(DeviceMigration deviceMigration) {
        // 迁移家庭圈数据
        // * 1.迁移ora_device_user 表， 不包含自己的绑定
        List<DeviceUser> deviceUsers = deviceUserService.selectDeviceUserList(Builder.of(DeviceUser::new).with(DeviceUser::setDeviceId, deviceMigration.getFromDeviceId()).build());
        for (DeviceUser deviceUser : deviceUsers) {
            if (deviceUser.getUserId() != null && !deviceUser.getUserId().equals(deviceMigration.getUserId())){
                deviceUser.setDeviceId(deviceMigration.getToDeviceId());
                deviceUserService.updateDeviceUser(deviceUser);
            }
        }

        // * 2.迁移 ora_voice_story 表
        List<VoiceStory> voiceStories = voiceStoryService.selectVoiceStoryList(Builder.of(VoiceStory::new).with(VoiceStory::setDeviceId, deviceMigration.getFromDeviceId()).build());
        for (VoiceStory voiceStory : voiceStories) {
            // TODO 这里不太确定要不要改用户的id 暂时先不改吧
//            voiceStory.setUserId(device.getAdminUserId());
            voiceStory.setDeviceId(deviceMigration.getToDeviceId());
            voiceStoryService.updateVoiceStory(voiceStory);
        }

        // * 3.迁移 ora_voice_memoir 表
        List<VoiceMemoir> voiceMemoirs = voiceMemoirService.selectVoiceMemoirList(Builder.of(VoiceMemoir::new).with(VoiceMemoir::setDeviceId, deviceMigration.getFromDeviceId()).build());
        for (VoiceMemoir voiceMemoir : voiceMemoirs) {
            // TODO 这里不太确定要不要改用户的id 暂时先不改吧
//            voiceStory.setUserId(device.getAdminUserId());
            voiceMemoir.setDeviceId(deviceMigration.getToDeviceId());
            voiceMemoirService.updateVoiceMemoir(voiceMemoir);
        }
    }

    @Override
    public void deviceVoiceDataMigration(DeviceMigration deviceMigration) {
        // * 3.迁移 ora_voice_record 表 迁移语音数据
        List<VoiceRecord> voiceRecords = voiceRecordService.selectVoiceRecordList(Builder.of(VoiceRecord::new).with(VoiceRecord::setDeviceId, deviceMigration.getFromDeviceId()).build());
        for (VoiceRecord voiceRecord : voiceRecords) {
            voiceRecord.setDeviceId(deviceMigration.getToDeviceId());
            voiceRecordService.updateVoiceRecord(voiceRecord);
        }
    }

}
